<template>
  <div class="detail-banner px-5">
    <router-link to="" class="flex items-center justify-between">
      <div class="flex items-center">
        <span
          class="text-white text-xl font-600 italic mr-2"
          style="font-style: italic !important"
          >百亿补贴</span
        >
        <span
          class="bg-white border-rounded-full block w-[20px] h-[20px] flex items-center justify-center"
        >
          <el-icon class="icon" color="#000"><ArrowRight /> </el-icon>
        </span>
      </div>
      <div class="flex items-center">
        <div :style="{ width: '35px', height: '45px' }">
          <el-image
            src="https://img30.360buyimg.com/jdg/jfs/t1/255477/28/24821/10835/67bc7c41F5ca05766/cf0ff48bf16bfde5.png"
            fit="fill"
          />
        </div>
        <span class="text-white text-3.5">买贵双倍赔</span>
      </div>
    </router-link>
  </div>
  <div class="product-detail-panel" ref="detailPanelRef">
    <div
      class="border-rounded-2xl bg-white px-2 pb-2"
      style="margin-top: -10px; scrollbar-width: none; overflow: scroll"
      @scroll="handleScroll"
      :style="{ height: stickyElementHeight + 'px' }"
    >
      <div class="flex justify-between items-baseline pt-3">
        <div class="pt-2.5 pb-1 text-xl font-600 line-clamp-2 hover:line-clamp-3 pr-2">
          <div class="inline-block" style="transform: translateY(2px)">
            <el-image
              class="tag"
              style="height: 20px; width: 56px"
              src="https://img20.360buyimg.com/img/jfs/t1/302383/7/3521/2256/681b1e83F45caf0de/88a1249b8b593555.png"
            ></el-image>
            <el-image
              class="tag"
              style="height: 25px"
              v-show="false"
              src="//img11.360buyimg.com/imagetools/jfs/t1/321285/19/19567/2324/6888b5adFc5f6939b/756a08d4f6c1a622.png"
            ></el-image>
            <el-image
              class="tag"
              style="height: 25px"
              v-show="false"
              src="//img14.360buyimg.com/imagetools/jfs/t1/328103/27/3763/2610/689b7a9fFb7166b64/ba1185b494c1948a.png"
            ></el-image>
          </div>

          李宁赤兔8PRO跑步鞋男鞋2025夏秋季新款肖战同款体测跑鞋ARPV003 标准白-10 43 (270mm)
        </div>

        <div
          class="border-l cursor-pointer"
          style="min-width: 70px; height: 55px"
          @click="handleCollect"
        >
          <div class="pt-2 flex flex-col items-center justify-center">
            <el-icon size="23"><Star /></el-icon>
            <span class="text-3">收藏</span>
          </div>
        </div>
      </div>
      <div class="flex justify-between pt-3 pb-2 sticky-element bg-white">
        <div class="flex justify-between items-center">
          <Price :price="500.65" size="large" />
          <span class="ml-1 text-3 bg-red-500 mx-1 px-1 py-1 text-white rounded-sm"
            >到手价</span
          >
          <div class="flex items-center text-3.5 text-gray-600">
            <span>￥560.15</span>
            <!-- <span>日常价</span> -->
          </div>
        </div>
        <div class="flex items-center text-3.5">
          <span class="mr-2 text-gray-500">累计评价 <i>2000+</i></span>
          <div
            class="flex items-center border-l px-1 cursor-pointer"
            @click="handleShowNotice"
          >
            <el-icon style="transform: translateY(-1px)"><Bell /></el-icon>
            <span class="ml-1">降价通知</span>
          </div>
        </div>
      </div>
      <div class="discount flex items-center py-2">
        <span
          class="text-3.5 mr-2 px-2 py-1 text-red-500 rounded-sm font-600 bg-red-200 hover:bg-red-100 cursor-pointer"
          >满100减50</span
        >
        <span
          class="text-3.5 mr-2 px-2 py-1 text-red-500 rounded-sm font-600 bg-red-200 hover:bg-red-100 cursor-pointer"
          >满100减50</span
        >
        <span
          class="text-3.5 mr-1 px-2 py-1 text-red-500 rounded-sm font-600 bg-red-200 hover:bg-red-100 cursor-pointer"
          >满100减50</span
        >
        <span class="ml-2 cursor-pointer" @click="isOpenDrawer = true"
          ><el-icon><ArrowRight /></el-icon
        ></span>
      </div>
      <div class="flex py-2">
        <div
          class="flex justify-between items-center py-2 px-2 cursor-pointer bg-gray-100 hover:bg-red-50"
        >
          <img
            src="//img10.360buyimg.com/imagetools/jfs/t1/261718/22/6550/560/67769350Fdeefaae3/4bdb3c60cbde63ae.png"
            style="width: 16px"
          />
          <span class="text-3.5 pl-1"
            >企业会员3000补贴，员工福利/商务馈赠一站式采购！</span
          >
          <span class="ml-1" style="height: 16px">
            <el-icon><ArrowRight /> </el-icon>
          </span>
        </div>
      </div>
      <div class="py-2">
        <div class="item flex">
          <span class="pl-2 text-3.5 text-gray-500" style="width: 75px">送至</span>
          <div class="flex items-center">
            <span class="text-3.5 text-gray-600 mr-2 line-height-none"
              >预计今天发货，9月13日24:00前送达</span
            >
            <el-tooltip
              class="box-item"
              effect="light"
              content="请以提交订单时为准"
              placement="bottom"
            >
              <div
                class="flex items-center text-3.5 cursor-pointer ml-1 line-height-none"
              >
                <span class="mr-1">包邮</span>
                <el-icon size="16" color="#666"><Warning /></el-icon>
              </div>
            </el-tooltip>
          </div>
        </div>
        <div class="item flex pt-1.5" v-click-outside="closeAddressDropdown">
          <span class="pl-2" style="width: 75px"></span>
          <div class="cursor-pointer mr-2 pos-relative flex-1" style="z-index: 209">
            <div class="flex items-baseline">
              <span class="text-3.5 text-red-500 font-600 mr-2">京东快递</span>
              <router-link to="">
                <span class="pr-2 text-3.5 text-red-500">送货上门</span></router-link
              >
              <div
                class="flex items-center hover:text-red-6"
                ref="addressElementRef"
                @click="handleAddressClick()"
              >
                <span class="pr-0.5 text-3.5">北京海淀区上地街道</span>
                <el-icon size="14"><ArrowDown /></el-icon>
              </div>
            </div>
            <Transition name="el-zoom-in-top">
              <div
                class="filter-dropdown pos-fixed"
                style="width: 630px; min-height: 200px; z-index: 209"
                :style="addressPanelStyle"
                v-show="showAddressDropdown"
              >
                <div class="h-2.5"></div>
                <div class="border rounded-lg bg-white pt-2 pos-relative box-shadow-md">
                  <b
                    class="arrow-down triangle"
                    style="
                      position: absolute;
                      top: -10px;
                      left: 50%;
                      transform: translateX(-50%);
                    "
                  ></b>
                  <div class="filter-dropdown-content px-1">
                    <AddressPanel @close="showAddressDropdown = false" />
                  </div>
                </div>
              </div>
            </Transition>
          </div>
        </div>
      </div>
      <div class="item pt-3.5">
        <SkusPanel :product="product" @update:selectedSpecs="updateSelectedSpecs" />
      </div>

      <div class="item flex mb-3">
        <span class="pl-2 text-3.5 text-gray-500" style="width: 75px; min-width: 75px"
          >服务</span
        >
        <div class="flex items-start pr-5">
          <div class="text-3.5 w-[75%]" style="line-height: 1.5">
            <router-link to="/service" class="hover:text-red-500"> 全国联保</router-link>
            ·
            <router-link to="/service" class="hover:text-red-500">一年质保</router-link> ·
            <router-link to="/service" class="hover:text-red-500">7天价保</router-link> ·
            免费上门退换 店铺发货&售后服务 ·<router-link
              to="/service"
              class="hover:text-red-500"
            >
              高价回收</router-link
            >
            支持7天无理由退货（一次性包装破损不支持）
          </div>
          <span class="text-gray-500 ml-2 cursor-pointer">
            <el-icon size="16">
              <ArrowUp />
            </el-icon>
          </span>
        </div>
      </div>
      <div class="item flex mb-3">
        <span
          class="pl-2 text-3.5 text-gray-500 pt-0.5"
          style="width: 75px; min-width: 75px"
          >京选服务
        </span>
        <div class="flex items-center">
          <Service />
        </div>
      </div>
      <div class="item flex mb-3">
        <span class="pl-2 text-3.5 text-gray-500" style="width: 75px; min-width: 75px"
          >白条分期
        </span>
        <div class="flex items-center">
          <Stage />
        </div>
      </div>
      <div style="height: 85px" v-show="!isStickyBottom"></div>
      <div
        class="border-t"
        ref="stickyElement"
        :class="{ 'is-sticky-box': !isStickyBottom }"
        :style="stickyStyles"
      >
        <div class="flex justify-between items-center py-5 px-5">
          <div class="flex flex-wrap items-center gap-4">
            <el-input-number v-model="count" size="large" :min="1" style="width: 140px" />
          </div>
          <button @click="addToCart" class="cart-btn px-4" size="large">
            加入购物车
          </button>
          <!-- 购买按钮 -->
          <button
            @click="toCheckout"
            class="cart-btn px-6"
            size="large"
            :disabled="!canAddToCart"
          >
            立即购买
          </button>
        </div>
      </div>
    </div>

    <div id="dorpdown-container"></div>
  </div>
  <!-- 降价通知弹窗 -->
  <teleport to="#target-container">
    <transition name="fade">
      <div class="pos-relative z-index-230">
        <el-dialog
          v-model="noticePopupVisible"
          title="降价通知"
          width="650"
          :before-close="handleNoticeClose"
          custom-class="border-rounded-2xl"
        >
          <template #title> <h3 class="font-600 text-lg">降价通知</h3></template>
          <div class="py-1">
            <div class="h-45">
              <p
                style="color: #f60; background-color: #fffbdb; line-height: 1"
                class="py-2 px-3"
              >
                当商品降价时，我们可以为您提供以下服务
              </p>
            </div>
          </div>
        </el-dialog>
      </div>
    </transition>
  </teleport>
  <!-- 优惠券弹窗 -->
  <teleport to="#target-container">
    <transition name="fade">
      <div>
        <el-drawer v-model="isOpenDrawer" :direction="direction" style="z-index: 1000">
          <template #header>
            <h2 class="font-600">全部频道</h2>
          </template>
          <template #default>
            <div class="tab-box"></div>
          </template>
        </el-drawer>
      </div>
    </transition>
  </teleport>
</template>
<script lang="ts" setup>
import { ref, onMounted, computed, watch } from "vue";
import * as Api from "@/api/index";
import { throttle } from "@/utils/util";
import type { DrawerProps } from "element-plus";
import {
  ArrowRight,
  Star,
  StarFilled,
  Bell,
  Warning,
  ArrowDown,
  Plus,
  Minus,
  ArrowUp,
} from "@element-plus/icons-vue";
import type { ProductInfo, Sku } from "@/api/types/product";

import Price from "@/components/common/Price.vue";
import SkusPanel from "@/components/product/SkusPanel.vue";
import AddressPanel from "@/components/ui/AddressPanel.vue";
import Service from "./Service.vue";
import Stage from "./Stage.vue";

const props = defineProps({
  product: {
    type: Object as () => ProductInfo,
    default: () => {},
  },
  isStickyBottom: {
    type: Boolean,
    default: false,
  },
});
const emits = defineEmits(["update:stickyZindex"]);

const stickyElementHeight = ref(878);
// 收藏、取消收藏
const handleCollect = () => {};
// 优惠券模块
const isOpenDrawer = ref(false);
const direction = ref<DrawerProps["direction"]>("rtl");

// 配送地址模块

const addressElementRef = ref<HTMLDivElement | null>(null);
const addressOffectLeft = ref(0);
const addressOffectTop = ref(0);
const showAddressDropdown = ref(false);
const closeAddressDropdown = () => {
  showAddressDropdown.value = false;
  emits("update:stickyZindex", 9);
};
const handleAddressClick = () => {
  showAddressDropdown.value = true;
  if (!addressElementRef.value) return;
  const rect = addressElementRef.value.getBoundingClientRect(); // 元素相对于视口的位置

  addressOffectLeft.value = rect.left;
  addressOffectTop.value = rect.top;
  emits("update:stickyZindex", 11);
};
const addressPanelStyle = computed(() => {
  return {
    top: addressOffectTop.value + "px",
    left: addressOffectLeft.value - 380 + "px",
  };
});
watch(showAddressDropdown, (newValue) => {
  if (!newValue) {
    setTimeout(() => {
      emits("update:stickyZindex", 9);
    }, 30);
  }
});
// --固定商品详情--
const detailPanelRef = ref<HTMLDivElement | null>(null);
const stickyElement = ref<HTMLDivElement | null>(null);
const isSticky = ref(false);
const stickyStyles = computed(() => {
  if (!detailPanelRef.value || !stickyElement.value) return;
  if (props.isStickyBottom) {
    return { width: "auto" };
  }
  return {
    width: detailPanelRef.value.offsetWidth - 2 + "px",
    left: detailPanelRef.value.getBoundingClientRect().left + "px",
    height: stickyElement.value.offsetHeight + "px",
  };
});

// --降价通知
const noticePopupVisible = ref(false);
const handleShowNotice = () => {
  noticePopupVisible.value = true;
  emits("update:stickyZindex", 9);
};
const handleNoticeClose = () => {
  noticePopupVisible.value = false;
};
// 购物模块
const count = ref(0);
const currentSku = ref<Sku | null>(null);
const selectedSpecs = ref(null);
const updateSelectedSpecs = (specs: any) => {
  selectedSpecs.value = specs;
};
// 购买按钮状态
const canAddToCart = computed(() => {
  if (!props.product) return false;
  if (!currentSku.value) return false;
  const stock = currentSku.value.stock ?? 0; // 若 stock 为 undefined，则默认为 0
  return (
    stock > 0 &&
    selectedSpecs.value &&
    Object.keys(selectedSpecs.value).length === props.product?.specs.length
  );
});

const buttonText = computed(() => {
  if (!canAddToCart.value) return "请选择规格";
  if (!currentSku.value) return;
  const stock = currentSku.value.stock ?? 0; // 若 stock 为 undefined，则默认为 0
  return stock > 0 ? "加入购物车" : "已售罄";
});

const addToCart = () => {
  console.log("添加SKU到购物车:", currentSku.value);
  // 调用购物车API...
};
const toCheckout = () => {};

const handleScroll = () => {
  // 获取目标元素的DOM引用
  if (!detailPanelRef.value) return;
  const rect = detailPanelRef.value.getBoundingClientRect(); // 获取元素边界矩形
  const viewportHeight = window.innerHeight; // 获取视口高度
  // 判断是否应该吸顶
  // isSticky.value = true;
  isSticky.value = viewportHeight - rect.bottom > 0;
  setTimeout(() => {
    showAddressDropdown.value = false;
  }, 350);
};
onMounted(() => {
  console.log("mounted", props.isStickyBottom);
  window.addEventListener("scroll", throttle(handleScroll, 150));
});
window.addEventListener("scroll", throttle(handleScroll, 150));
</script>
<style lang="scss" scoped>
:root {
  --el-border-radius-base: 10px !important;
}

.sticky-element {
  position: sticky; /* 声明为粘性定位 */
  top: 0; /* 距离视口顶部的阈值（触发固定的临界值） */
  /* 可选：bottom/right/left 用于其他方向的固定 */
}
.is-sticky-box {
  position: fixed;
  bottom: 0;
  width: auto;
  z-index: 90;
  height: 85px;
  /* 可以添加一些吸附后的样式 */
  background-color: #fff;
  box-shadow: 0 2px 3px rgba(0, 0, 0, 0.05);
}

// 按钮-购物车
.cart-btn {
  @apply py-2.5 bg-red-400  text-white font-600 rounded-sm cursor-pointer no-border;
}
.cart-btn:hover {
  border: 1px solid rgb(250, 119, 119) !important;
}
</style>
